﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Telerik.Web.UI;

namespace Quanly
{
    public partial class NguoiDung : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridFilterFunction.IllegalStrings = new[] { " LIKE " };
        }

        #region Methods

        private void BindUserGrid()
        {
            var users = WebProvider.Provider.User.GetAllUsers();
            if (users == null) return;
            users = users.ToList();
            gridUser.DataSource = users;
            gridUser.VirtualItemCount = users.Count();
            
        }

        private void UpdateUserStatus(int userId)
        {
            var msgReturn = WebProvider.Provider.User.UpdateUserStatus(userId);
            if(msgReturn.IsSuccess) gridUser.Rebind();
        }

        #endregion

        #region events

        protected void gridUser_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem)
            {
                return;
            }
            var item = e.Item;
            var dataItem = (GridDataItem) item;
            var user = (QLBH_User)item.DataItem;
            dataItem["Status"].BackColor = user.Status == 1 ? Color.ForestGreen : Color.Firebrick;
            var aDel = item.FindControl("aDel") as LinkButton;
            if (aDel != null)
            {
                aDel.OnClientClick = "return delUser('" +user.UserName+ "','"+user.Status+"')";
            }
        }

        protected void gridUser_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "deluser")
            {
                var userId = int.Parse(e.CommandArgument.ToString());
                UpdateUserStatus(userId);
            }
        }

        protected void gridUser_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            BindUserGrid();
        }

        #endregion
    }
}